#include "App_message.h"

/*
字符数组:  1 2 4 XXabcd
json字符串: {"conn_type": 1, "id": "5858", "msg": "61626364"}
*/
char *App_Message_CharArrayToJson(char *array, int len)
{
    // 从array中提取conn_type、id_len,msg_len,id,msg
    int conn_type = array[0];
    int id_len = array[1];
    int msg_len = array[2];

    // 检查id_len和msg_len是否超出了数组的长度
    if (len != 3 + id_len + msg_len)
    { // 3是前面三个字节的长度
        log_debug("字符串的长度错误 ");
        return NULL;
    }

    // 从array中提取id和msg
    char id[id_len];
    char msg[msg_len];
    memcpy(id, array + 3, id_len);
    memcpy(msg, array + 3 + id_len, msg_len);

    // 生成id和msg的16进制字符串
    char *id_hex = App_Common_CharArrayToHex(id, id_len);
    char *msg_hex = App_Common_CharArrayToHex(msg, msg_len);

    // 拼接json字符串
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "conn_type", conn_type);
    cJSON_AddStringToObject(root, "id", id_hex);
    cJSON_AddStringToObject(root, "msg", msg_hex);
    char *json = cJSON_PrintUnformatted(root);

    // 释放内存
    cJSON_Delete(root);
    free(id_hex);
    free(msg_hex);
    // 返回json字符串
    return json;
}

int App_Message_JsonToCharArray(char *json, char *arraybuff, int buff_size)
{
    // 解析字符串
    cJSON *root = cJSON_Parse(json);
    // 从json中得到conn_type、id_hex、msg_hex
    cJSON *conn_type_obj = cJSON_GetObjectItem(root, "conn_type");
    cJSON *id_obj = cJSON_GetObjectItem(root, "id");
    cJSON *msg_obj = cJSON_GetObjectItem(root, "msg");
    int conn_type = conn_type_obj->valueint;
    char *id_hex = id_obj->valuestring;
    char *msg_hex = msg_obj->valuestring;

    // 将id_hex和msg_hex转换为id和msg，并得到id_len和msg_len
    int id_len = 0;
    int msg_len = 0;
    char *id = App_Common_HexToCharArray(id_hex, &id_len);
    char *msg = App_Common_HexToCharArray(msg_hex, &msg_len);

    // 计算字符数组的长度
    int chars_len = 3 + id_len + msg_len;
    // 检查buf_size
    if (buff_size< chars_len)
    {
        log_error("字符数组容器大小不足");
        return -1;
    }

    // 将conn_type、id_len、msg_len、id、msg写入arraybuff 1 2 4 XXabcd
    arraybuff[0] = conn_type;
    arraybuff[1] = id_len;
    arraybuff[2] = msg_len;
    memcpy(arraybuff + 3, id, id_len);
    memcpy(arraybuff + 3 + id_len, msg, msg_len);
    
    // 释放内存
    cJSON_Delete(root);
    free(id);
    free(msg);
    return chars_len;
}
